home *** CD-ROM | disk | FTP | other *** search
- Path: news.cern.ch!danpop
- From: danpop@mail.cern.ch (Dan Pop)
- Newsgroups: comp.lang.c
- Subject: Re: char* still alive after free ???
- Date: 15 Apr 96 17:33:20 GMT
- Organization: CERN European Lab for Particle Physics
- Message-ID: <danpop.829589600@news.cern.ch>
- References: <317269EA.11BB93C2@studbox.uni-stuttgart.de>
- NNTP-Posting-Host: ues5.cern.ch
- Mime-Version: 1.0
- Content-Type: text/plain; charset=US-ASCII
- Content-Transfer-Encoding: 7bit
- X-Newsreader: NN version 6.5.0 #7 (NOV)
-
- In <317269EA.11BB93C2@studbox.uni-stuttgart.de> Markus Heller <Markus.Heller@studbox.uni-stuttgart.de> writes:
-
- >I have a global variable :
- >
- >char *text=NULL;
- >
- >I want to use it to store different "strings" (at diffreent times).
- >E.g., if I want to sore 10 characters in text, I do a
- >text=(char *) malloc(10*sizeof(char));
-
- 1. 10*sizeof(char) is overkill, plain 10 would do as well.
-
- 2. If you want to store 10 charaters as a C string, allocate space for
- 11 characters. C strings are null-terminated.
-
- 3. The cast is a bad idea. Don't use it.
-
- >When I want to use text to store 3 other characters, I first do a
- >free(text); text=NULL; and finally a
- >text=(char *) malloc(3*sizeof(char));
- >But to my surprise there are still the 4thh to 10th charcter of
- >text contained before the free(text)/malloc... ???
-
- Why not? The point is that, after text = malloc(3), it is _illegal_
- to attempt to access the 4th to 10th characters. Your program could
- simply crash and burn with a segmentation fault. text is now pointing
- to the first character of an array of 3 characters, period.
-
- >This happens under linux, but why ?
-
- For the simple reason that malloc is returning the same address as in
- the previous call and the old characters have retained their values.
- Calling free() isn't likely to alter the contents of the memory block
- being returned to the memory allocator.
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-